/*
 * @Author: dvlproad
 * @Date: 2022-12-27 18:42:49
 * @LastEditors: dvlproad
 * @LastEditTime: 2023-10-31 18:09:08
 * @Description: 
 */
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// 引入库文件
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

import '../base/javascript_channel.dart';

class TSWebViewJSPage extends StatefulWidget {
  const TSWebViewJSPage({super.key});

  @override
  State<TSWebViewJSPage> createState() => TSWebViewJSPageState();
}

class TSWebViewJSPageState extends State<TSWebViewJSPage> {
  late WebViewController _webController;

  late WebViewWidget _webViewWidget;

  bool _showLoading = false;

  @override
  void initState() {
    super.initState();

    _webController = defaultController;
    _webViewWidget = WebViewWidget(controller: _webController);

    _addJs();
    _loadRequest();
  }

  _loadRequest() {
    // _webController.loadRequest(Uri.parse(widget.url!));

    // String fileHtmlContents =
    //     await rootBundle.loadString('assets/html/dvlp_mini_program_demo_postMessage.html');
    // _webController.loadHtmlString(Uri.dataFromString(fileHtmlContents,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString());
    _webController.loadFlutterAsset(
        'assets/html/dvlp_mini_program_demo_postMessage.html');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('h5页面'),
      ),
      body: _webViewWidget,
    );
  }

  _addJs() {
    Set<JavascriptChannel> javascriptChannels = {
      JavascriptChannel(
        name: "h5CallBridgeAction_showAppToast",
        onMessageReceived: (JavaScriptMessage message) {
          debugPrint("h5调用原生方法，原生收到h5发来的信息:${message.message}");
        },
      ),
      JavascriptChannel(
        name: "h5CallBridgeAction_jumpAppPage",
        onMessageReceived: (JavaScriptMessage message) {
          debugPrint("h5调用原生方法，原生收到h5发来的信息:${message.message}");
        },
      ),
    };

    for (var channel in javascriptChannels) {
      _webController.addJavaScriptChannel(
        channel.name ?? "unkonw",
        onMessageReceived: channel.onMessageReceived,
      );
    }
  }

  WebViewController get defaultController {
    PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

// body: WebView(
//         initialUrl: '',
//         onWebViewCreated: (WebViewController controller) {
//           _webController = controller;
//           _loadHtmlFromAssets();
//         },

//       ),

    return WebViewController.fromPlatformCreationParams(params)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0xfff1f1f1))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            if (mounted) {
              setState(() {
                _showLoading = true;
              });
            }
          },
          onPageFinished: (String url) {
            // _webViewWidget.getTitle().then((title) {
            //   if (mounted) {
            //   setState(() {
            //     _title =  title;
            //   });
            // }
            // });
            if (mounted) {
              setState(() {
                _showLoading = false;
              });
            }
          },
          onProgress: (int progress) {
            // _progressValue = progress / 100;
            // ToastUtil.showMessage('$progress%');

            if (mounted) setState(() {});
          },
          onWebResourceError: (WebResourceError error) async {
            _webController.getTitle().then((title) {});
            // _onErrorInnerHTML();
            //webview页面加载失败log
          },
        ),
      );
  }
}
